import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import { refreshToken as apiRefreshToken } from '@/apis/user'

const routes = [
    {
        path: '/',
        name: 'Home',
        component: () => import('../views/Home.vue'),
        meta: { requiresAuth: true } // 需要登录才能访问
    },
    {
        path: '/file',
        name: 'File',
        component: () => import('../views/File.vue'),
        meta: { requiresAuth: true } // 需要登录才能访问
    },
    {
        path: '/profile',
        name: 'Profile',
        component: () => import('../views/Profile.vue'),
        meta: { requiresAuth: true } // 需要登录才能访问
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/Login.vue'),
        meta: { requiresGuest: true } // 已登录用户不能访问
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('../views/Register.vue'),
        meta: { requiresGuest: true } // 已登录用户不能访问
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const userStore = useUserStore()
    
    // 初始化用户状态（从localStorage恢复）
    if (!userStore.token && localStorage.getItem('token')) {
        userStore.initUserState()
    }
    
    // 每日首次打开自动刷新：按日期去重
    const today = new Date().toISOString().slice(0, 10)
    const last = localStorage.getItem('lastRefreshDate')
    if (userStore.isLogin && userStore.refreshToken && last !== today) {
        localStorage.setItem('lastRefreshDate', today)
        apiRefreshToken(userStore.refreshToken).then((res) => {
            userStore.updateTokens({ token: res.data?.token || res.token, refreshToken: res.data?.refreshToken || res.refreshToken })
        }).catch(() => {
            userStore.logout()
            if (router.currentRoute.value.name !== 'Login') {
                router.push({ name: 'Login', query: { redirect: to.fullPath } })
            }
        })
    }
    
    // 检查是否需要登录
    if (to.meta.requiresAuth) {
        if (!userStore.isLogin) {
            ElMessage.warning('请先登录')
            next({
                name: 'Login',
                query: { redirect: to.fullPath } // 保存目标路径，登录后跳转
            })
            return
        }
    }
    
    // 检查是否需要游客状态（已登录用户不能访问登录/注册页）
    if (to.meta.requiresGuest) {
        if (userStore.isLogin) {
            // 已登录用户访问登录/注册页时，跳转到首页
            next({ name: 'Home' })
            return
        }
    }
    
    next()
})

export default router
